<template>
  <div class="ground-wave-form">
    <XcForm :key="tableKey" class="form-view" ref="formView" :config="config" :values="formData" :colProps="4" labelPosition="right"></XcForm>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import type { ColumnItem, XcFormInstance } from "@xc-components/xc-form/types";
import { getGroundDirectionAccuracies, updateGeneratorInfo } from "../../../../api/test/index";
import type { GeneratorInfo } from "../../../../api/test/index.d";
import { useRoute } from "vue-router";
const route = useRoute();

const props = withDefaults(defineProps<{ tableList: any[] }>(), {
  tableList: () => []
});
const emits = defineEmits(["updateList"]);
const taskId = route.query.taskId;
watch(
  () => props.tableList,
  (val) => {
    const nameRow = config.value.find((it) => it.prop === "id");
    if (nameRow) {
      nameRow.options = val.map((it) => ({ label: it.name, value: it.id }));
      getGroudWaveList(props.tableList[0] || {});
    }
  }
);
const formView = ref<XcFormInstance<GeneratorInfo[]> | null>(null);
const config = ref<ColumnItem[]>([
  {
    label: "发射源",
    prop: "id",
    type: "select",
    options: [],
    required: true,
    onChange: async (val) => {
      const row = props.tableList.find((it) => it.id === val);
      if (row) {
        getGroudWaveList(row);
      }
    }
  },
  { label: "经度", prop: "longitude", inputType: "number" },
  { label: "纬度", prop: "latitude", inputType: "number" },
  { label: "距离", prop: "distance", inputType: "number" },
  { label: "理论示向角", prop: "realAngle", inputType: "number" }
]);
const formData = ref({} as GeneratorInfo);
const tableKey = ref(+new Date());

onMounted(() => {
  config.value.forEach((item) => {
    if (!item.onChange) {
      item.onChange = async () => {
        formData.value = { ...formData.value, ...(formView.value?.data || {}) };
        const index = props.tableList.findIndex((it) => it.id === formData.value.id);
        props.tableList[index] = formData.value;
        await updateGeneratorInfo({ generator: formData.value }, { taskId });
      };
    }
  });
  tableKey.value = +new Date();
});
const getGroudWaveList = async (row: GeneratorInfo) => {
  formData.value = JSON.parse(JSON.stringify(row));
  const { data } = await getGroundDirectionAccuracies({ generatorId: row.id }, { taskId });
  emits("updateList", data || []);
};
</script>

<style lang="scss" scoped></style>
